#include "image.h"

#include <stdlib.h>
#include <stdio.h>

void Image_init(Image* image)
{
  image->width = 0;
  image->height = 0;
  image->colour = NULL;
}

void Image_free(Image* image)
{
  delete[] image->colour;
  
  image->width = 0;
  image->height = 0;
  image->colour = NULL;
}

ImageError Image_load(Image* image, const char* filename)
{
  FILE* file = fopen(filename, "rb");
  uint32 width;
  uint32 height;
  uint8 bytes_per_pixel;
  
  if (!file)
  {
    return IMAGE_ERROR_NOT_OPEN_FILE;
  }
  
  fread(&width, 4, 1, file);
  fread(&height, 4, 1, file);
  fread(&bytes_per_pixel, 1, 1, file);
  
  if (bytes_per_pixel != 4)
  {
    return IMAGE_ERROR_WRONG_FORMAT;
  }
  
  image->width = width;
  image->height = height;
  image->colour = new Colour[width * height];
  
  fread(image->colour, 4, width * height, file);
  
  fclose(file);
  
  return IMAGE_ERROR_OK;
}

ImageError Image_save(const Image& image, const char* filename)
{
  FILE* file = fopen(filename, "rb");
  uint8 bytes_per_pixel = 4;
  
  if (!file)
  {
    return IMAGE_ERROR_NOT_OPEN_FILE;
  }
  
  fwrite(&image.width, 4, 1, file);
  fwrite(&image.height, 4, 1, file);
  fwrite(&bytes_per_pixel, 1, 1, file);
  fwrite(image.colour, 4, image.width * image.height, file);
  
  return IMAGE_ERROR_OK;
}
